const { Service } = require('egg')
const iconv = require('iconv-lite') // 导入iconv-lite模块
const { tableToList } = require('../utils/tools')

module.exports = class GradeService extends Service {
  /**
   * * 课程成绩查询
   * @param {String} term  学期
   * @return {Array} *
   */
  async table(term = '') {
    const [xn, sjxzRaw, xqRaw] = term ? term.split('-') : ['', '', '']
    const sjxz = sjxzRaw ? 'sjxz3' : 'sjxz1'
    let xq
    if (term) { xq = xqRaw === '1' ? '0' : '1' }
    const Cookie = this.ctx.state.Cookie
    const apiUrl = `${this.ctx.state.baseUrl}/cssfjw/student/xscj.stuckcj_data.jsp`
    const res = await this.ctx.curl(apiUrl, {
      method: 'POST',
      data: {
        xq,
        xn,
        sjxz,
        ysyx: 'yxcj',
      },
      headers: {
        Cookie,
        Referer: 'http://58.20.34.197:10115/cssfjw/student/xscj.stuckcj.jsp?menucode=S40303',
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
      },
      timeout: 10000,
    })
    const gbkString = iconv.decode(res.data, 'gbk')

    // const header = [ '名称', '性质/类别', '学分', '成绩', '获得学分' ];
    const header = ['名称', '性质/类别', '学分', '成绩', '学分', '绩点', '学分绩点']

    if (res.status === 200) {
      try {
        const data = tableToList(gbkString, 'body table tbody', '')

        // 开始处理
        const dataxq = JSON.parse(JSON.stringify(data))
        const data2 = []
        const dataUp = []
        let k = 0
        const xq2 = []
        for (const i of dataxq) { // 分离学年学期
          if (i.length === 1) {
            i[0] = i[0].split('学年学期：')[1]
            if (i[0].includes('学年第一学期')) {
              i[0] = i[0].replace('学年第一学期', '-1')
            } else if (i[0].includes('学年第二学期')) {
              i[0] = i[0].replace('学年第二学期', '-2')
            }
            xq2.push(i)
          }
        }
        for (const i in data) { // 分离成绩信息
          if (data[i].length === 12) {
            data[i][1] = data[i][1].replace(/\[.*?\]/g, '')
          }
          if (i < data.length - 12) {
            data2.push(data[i])
          }
        }
        for (const i in data2) { // 删除多余信息
          data2[i].splice(0, 1)
          data2[i].splice(2, 1)
          data2[i].splice(3, 1)
          data2[i].splice(3, 1)
          data2[i].splice(7, 1)
        }
        for (const i of data2) { // 删除空白信息
          if (i.length === 0) {
            dataUp.push(new Array(''))
          }
          if (i.length !== 0) {
            if (!dataUp[k]) {
              dataUp[k] = []
            }
            dataUp[k].push(i)
          } else if (i.length === 0) {
            i.splice(0, 1)
            k++
          }
        }
        // console.log('data2', data2)
        for (const q of dataUp) {
          for (const i of q) {
            if (i.length !== 0) {
              const temp = i[1] // 交换位置
              // i[1] = i[2];
              // i[1] = i[2].replace(/课\//g, '');
              i[1] = i[2].replace(/课/g, '')
              i[2] = temp
              i[3] = { score: i[3] }
            }
          }
          if (q[0] === '') {
            q.splice(0, 1)
          }
        }
        dataUp.splice(0, 1)
        const dataJson = {}
        for (let i = 0; i < xq.length; i++) {
          dataJson[xq[i]] = dataUp[i]
        }
        // 结束处理

        return { table: dataJson, header }
      } catch (err) {
        console.log('err', err)
        throw err
      }
    }
    return { table: {}, header }
  }

  /**
   * * 成绩占比数据请求
   * @param {string} link 占比详情请求地址
   * @return {Object} *
   */
  async proportion(link) {
    const Cookie = this.ctx.state.Cookie
    const apiUrl = encodeURI(link)
    const res = await this.ctx.curl(apiUrl, {
      method: 'GET',
      headers: {
        Cookie,
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
      },
      timeout: 10000,
    })
    if (res.status === 200) {
      try {
        const tableList = tableToList(res.data.toString(), '#dataList')
        return tableList
      } catch (err) {
        console.log('err', err)
        throw err
      }
    }
    return {}
  }
}
